package com.dddpeter.app.service;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.dddpeter.app.entity.User;
import com.dddpeter.app.repository.UserMapper;
import com.dddpeter.app.repository.ArticleMapper;
import com.dddpeter.app.util.PasswordUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.List;
import java.util.Optional;

@Service
@Transactional
public class UserService {
    
    @Autowired
    private UserMapper userMapper;
    
    @Autowired
    private ArticleMapper articleMapper;
    
    public List<User> getAllUsers() {
        return userMapper.selectList(null);
    }
    
    public Optional<User> getUserById(Long id) {
        return Optional.ofNullable(userMapper.selectById(id));
    }
    
    public Optional<User> getUserByUsername(String username) {
        return Optional.ofNullable(userMapper.findByUsername(username));
    }
    
    public Optional<User> getUserByEmail(String email) {
        return Optional.ofNullable(userMapper.findByEmail(email));
    }
    
    public User createUser(User user) {
        if (userMapper.existsByUsername(user.getUsername())) {
            throw new RuntimeException("用户名已存在: " + user.getUsername());
        }
        if (userMapper.existsByEmail(user.getEmail())) {
            throw new RuntimeException("邮箱已存在: " + user.getEmail());
        }
        
        // 加密密码
        if (user.getPassword() != null && !user.getPassword().trim().isEmpty()) {
            user.setPassword(PasswordUtil.encode(user.getPassword()));
        }
        
        userMapper.insert(user);
        return user;
    }
    
    public User updateUser(Long id, User userDetails) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在，ID: " + id);
        }
        
        // 检查用户名是否被其他用户使用
        if (!user.getUsername().equals(userDetails.getUsername()) && 
            userMapper.existsByUsername(userDetails.getUsername())) {
            throw new RuntimeException("用户名已存在: " + userDetails.getUsername());
        }
        
        // 检查邮箱是否被其他用户使用
        if (!user.getEmail().equals(userDetails.getEmail()) && 
            userMapper.existsByEmail(userDetails.getEmail())) {
            throw new RuntimeException("邮箱已存在: " + userDetails.getEmail());
        }
        
        user.setUsername(userDetails.getUsername());
        user.setEmail(userDetails.getEmail());
        user.setFullName(userDetails.getFullName());
        
        // 更新权限字段
        if (userDetails.getCanLogin() != null) {
            user.setCanLogin(userDetails.getCanLogin());
        }
        if (userDetails.getIsAdmin() != null) {
            user.setIsAdmin(userDetails.getIsAdmin());
        }
        
        // 如果提供了新密码，则更新密码（需要加密）
        if (userDetails.getPassword() != null && !userDetails.getPassword().trim().isEmpty()) {
            user.setPassword(PasswordUtil.encode(userDetails.getPassword()));
        }
        
        userMapper.updateById(user);
        return user;
    }
    
    public void deleteUser(Long id) {
        User user = userMapper.selectById(id);
        if (user == null) {
            throw new RuntimeException("用户不存在，ID: " + id);
        }
        
        // 检查是否有文章引用该用户
        // 如果有文章，可以选择：
        // 1. 删除该用户的所有文章
        // 2. 将文章的作者ID设为null或设置为其他用户
        // 3. 不允许删除有文章的用户
        
        // 这里选择方案3：不允许删除有文章的用户
        if (articleMapper.countByAuthorId(id) > 0) {
            throw new RuntimeException("该用户有发布的文章，无法删除。请先删除或转移该用户的所有文章。");
        }
        
        userMapper.deleteById(id);
    }
    
    public List<User> searchUsersByName(String name) {
        return userMapper.findByFullNameContaining(name);
    }
    
    public List<User> getUsersCreatedAfter(LocalDateTime startDate) {
        return userMapper.findUsersCreatedAfter(startDate);
    }
    
    public long getUserCount() {
        return userMapper.selectCount(null);
    }
}
